<template>
  <div class="user-agreement-container">
    <el-card class="agreement-card">
      <template #header>
        <div class="card-header">
          <h2>用户协议和隐私政策</h2>
          <div class="header-actions">
            <el-button @click="refreshPolicies" :icon="Refresh" size="small">
              刷新
            </el-button>
            <el-button type="primary" @click="showCreateDialog = true" v-if="isAdmin">
              创建新政策
            </el-button>
            <el-button @click="showManageDialog = true" v-if="isAdmin">
              管理政策
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="agreement-content">
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="用户协议" name="agreement">
            <div class="tab-content">
              <div v-if="userAgreement" v-html="userAgreement.content" class="policy-content"></div>
              <div v-else class="no-content">
                <el-empty description="暂无用户协议内容" />
              </div>
              <div class="policy-info" v-if="userAgreement">
                <p><strong>版本：</strong>{{ userAgreement.version }}</p>
                <p><strong>发布日期：</strong>{{ formatDate(userAgreement.publishDate) }}</p>
                <p><strong>状态：</strong>
                  <el-tag :type="userAgreement.isActive ? 'success' : 'info'">
                    {{ userAgreement.isActive ? '已发布' : '未发布' }}
                  </el-tag>
                </p>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="隐私政策" name="privacy">
            <div class="tab-content">
              <div v-if="privacyPolicy" v-html="privacyPolicy.content" class="policy-content"></div>
              <div v-else class="no-content">
                <el-empty description="暂无隐私政策内容" />
              </div>
              <div class="policy-info" v-if="privacyPolicy">
                <p><strong>版本：</strong>{{ privacyPolicy.version }}</p>
                <p><strong>发布日期：</strong>{{ formatDate(privacyPolicy.publishDate) }}</p>
                <p><strong>状态：</strong>
                  <el-tag :type="privacyPolicy.isActive ? 'success' : 'info'">
                    {{ privacyPolicy.isActive ? '已发布' : '未发布' }}
                  </el-tag>
                </p>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>

    <!-- 创建政策对话框 -->
    <el-dialog v-model="showCreateDialog" :title="`创建新${createForm.policyType === 'user_agreement' ? '用户协议' : '隐私政策'}`" width="60%">
      <!-- 调试信息 -->
      <div class="debug-info" style="margin-bottom: 20px; padding: 10px; background-color: #f5f7fa; border-radius: 4px; font-size: 12px;">
        <p><strong>当前创建的政策信息：</strong></p>
        <p>政策类型: {{ createForm.policyType === 'user_agreement' ? '用户协议' : '隐私政策' }}</p>
        <p>版本: {{ createForm.version || '未填写' }}</p>
      </div>
      
      <el-form :model="createForm" :rules="createRules" ref="createFormRef" label-width="100px">
        <el-form-item label="政策类型" prop="policyType">
          <el-select v-model="createForm.policyType" placeholder="请选择政策类型">
            <el-option label="用户协议" value="user_agreement" />
            <el-option label="隐私政策" value="privacy_policy" />
          </el-select>
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-input v-model="createForm.version" placeholder="请输入版本号，如：1.0" />
        </el-form-item>
        <el-form-item label="政策内容" prop="content">
          <SimpleRichEditor
            v-model="createForm.content"
            placeholder="请输入政策内容，支持富文本格式"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="handleCreatePolicy" :loading="creating">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 管理政策对话框 -->
    <el-dialog v-model="showManageDialog" title="政策管理" width="80%">
      <div class="policy-management">
        <el-tabs v-model="manageActiveTab" type="border-card">
          <el-tab-pane label="用户协议管理" name="manage-agreement">
            <PolicyManagementTable 
              :policies="userAgreementList" 
              @refresh="loadUserAgreements"
              @edit="handleEditPolicy"
              @publish="handlePublishPolicy"
              @deactivate="handleDeactivatePolicy"
              @delete="handleDeletePolicy"
            />
          </el-tab-pane>
          <el-tab-pane label="隐私政策管理" name="manage-privacy">
            <PolicyManagementTable 
              :policies="privacyPolicyList" 
              @refresh="loadPrivacyPolicies"
              @edit="handleEditPolicy"
              @publish="handlePublishPolicy"
              @deactivate="handleDeactivatePolicy"
              @delete="handleDeletePolicy"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 编辑政策对话框 -->
    <el-dialog v-model="showEditDialog" :title="`编辑${editForm.policyType === 'user_agreement' ? '用户协议' : '隐私政策'}`" width="60%">
      <!-- 调试信息 -->
      <div class="debug-info" style="margin-bottom: 20px; padding: 10px; background-color: #f5f7fa; border-radius: 4px; font-size: 12px;">
        <p><strong>当前编辑的政策信息：</strong></p>
        <p>政策ID: {{ editForm.policyId }}</p>
        <p>政策类型: {{ editForm.policyType === 'user_agreement' ? '用户协议' : '隐私政策' }}</p>
        <p>版本: {{ editForm.version }}</p>
      </div>
      
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="政策类型" prop="policyType">
          <el-select v-model="editForm.policyType" placeholder="请选择政策类型">
            <el-option label="用户协议" value="user_agreement" />
            <el-option label="隐私政策" value="privacy_policy" />
          </el-select>
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-input v-model="editForm.version" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="政策内容" prop="content">
          <SimpleRichEditor
            v-model="editForm.content"
            placeholder="请输入政策内容，支持富文本格式"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleUpdatePolicy" :loading="updating">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { 
  getPolicyList, 
  createPolicy, 
  updatePolicy, 
  publishPolicy, 
  deactivatePolicy, 
  deletePolicy 
} from '@/api/policy'
import PolicyManagementTable from './components/PolicyManagementTable.vue'
import SimpleRichEditor from '@/components/SimpleRichEditor.vue'

// 响应式数据
const activeTab = ref('agreement')
const manageActiveTab = ref('manage-agreement')
const showCreateDialog = ref(false)
const showManageDialog = ref(false)
const showEditDialog = ref(false)
const creating = ref(false)
const updating = ref(false)

// 政策数据
const userAgreement = ref(null)
const privacyPolicy = ref(null)
const userAgreementList = ref([])
const privacyPolicyList = ref([])

// 表单数据
const createForm = ref({
  policyType: 'user_agreement',
  version: '',
  content: ''
})

const editForm = ref({
  policyId: '',
  policyType: '',
  version: '',
  content: ''
})

// 表单引用
const createFormRef = ref()
const editFormRef = ref()

// 表单验证规则
const createRules = {
  policyType: [{ required: true, message: '请选择政策类型', trigger: 'change' }],
  version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  content: [{ required: true, message: '请输入政策内容', trigger: 'blur' }]
}

const editRules = {
  policyType: [{ required: true, message: '请选择政策类型', trigger: 'change' }],
  version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  content: [{ required: true, message: '请输入政策内容', trigger: 'blur' }]
}

// 计算属性
const isAdmin = computed(() => {
  // 这里可以根据实际权限判断逻辑来设置
  return true
})

// 方法
const loadActivePolicies = async () => {
  try {
    // 首先尝试获取活跃的政策
    const [agreementRes, privacyRes] = await Promise.all([
      getPolicyList({ policyType: 'user_agreement', isActive: true }),
      getPolicyList({ policyType: 'privacy_policy', isActive: true })
    ])
    
    // 处理用户协议
    if (agreementRes.code === 200 && agreementRes.data && agreementRes.data.length > 0) {
      userAgreement.value = agreementRes.data[0]
    } else {
      // 如果没有活跃的，获取最新版本
      const latestAgreementRes = await getPolicyList({ policyType: 'user_agreement' })
      if (latestAgreementRes.code === 200 && latestAgreementRes.data && latestAgreementRes.data.length > 0) {
        userAgreement.value = latestAgreementRes.data[0]
      } else {
        userAgreement.value = null
      }
    }
    
    // 处理隐私政策
    if (privacyRes.code === 200 && privacyRes.data && privacyRes.data.length > 0) {
      privacyPolicy.value = privacyRes.data[0]
    } else {
      // 如果没有活跃的，获取最新版本
      const latestPrivacyRes = await getPolicyList({ policyType: 'privacy_policy' })
      if (latestPrivacyRes.code === 200 && latestPrivacyRes.data && latestPrivacyRes.data.length > 0) {
        privacyPolicy.value = latestPrivacyRes.data[0]
      } else {
        privacyPolicy.value = null
      }
    }
  } catch (error) {
    console.error('加载活跃政策失败:', error)
    ElMessage.error('加载政策内容失败')
  }
}

const loadUserAgreements = async () => {
  try {
    const res = await getPolicyList({ policyType: 'user_agreement' })
    if (res.code === 200) {
      userAgreementList.value = res.data
      console.log('加载的用户协议列表:', userAgreementList.value)
    }
  } catch (error) {
    console.error('加载用户协议列表失败:', error)
    ElMessage.error('加载用户协议列表失败')
  }
}

const loadPrivacyPolicies = async () => {
  try {
    const res = await getPolicyList({ policyType: 'privacy_policy' })
    if (res.code === 200) {
      privacyPolicyList.value = res.data
      console.log('加载的隐私政策列表:', privacyPolicyList.value)
    }
  } catch (error) {
    console.error('加载隐私政策列表失败:', error)
    ElMessage.error('加载隐私政策列表失败')
  }
}

const handleCreatePolicy = async () => {
  try {
    await createFormRef.value.validate()
    creating.value = true
    
    const res = await createPolicy(createForm.value)
    if (res.code === 200) {
      ElMessage.success('政策创建成功')
      showCreateDialog.value = false
      
      // 保存政策类型用于刷新
      const createdPolicyType = createForm.value.policyType
      
      // 重置表单
      createForm.value = { policyType: 'user_agreement', version: '', content: '' }
      
      // 刷新对应的列表
      if (createdPolicyType === 'user_agreement') {
        await loadUserAgreements()
      } else {
        await loadPrivacyPolicies()
      }
      
      // 刷新活跃政策
      await loadActivePolicies()
    } else {
      ElMessage.error(res.message || '创建失败')
    }
  } catch (error) {
    console.error('创建政策失败:', error)
    ElMessage.error('创建政策失败')
  } finally {
    creating.value = false
  }
}

const handleEditPolicy = (policy) => {
  console.log('编辑政策，接收到的政策对象:', policy)
  editForm.value = {
    policyId: policy.policyId,
    policyType: policy.policyType,
    version: policy.version,
    content: policy.content
  }
  console.log('设置后的编辑表单:', editForm.value)
  showEditDialog.value = true
}

const handleUpdatePolicy = async () => {
  try {
    await editFormRef.value.validate()
    updating.value = true
    
    const res = await updatePolicy(editForm.value.policyId, {
      policyType: editForm.value.policyType,
      version: editForm.value.version,
      content: editForm.value.content
    })
    
    if (res.code === 200) {
      ElMessage.success('政策更新成功')
      showEditDialog.value = false
      
      // 刷新数据
      await loadActivePolicies()
      await loadUserAgreements()
      await loadPrivacyPolicies()
    } else {
      ElMessage.error(res.message || '更新失败')
    }
  } catch (error) {
    console.error('更新政策失败:', error)
    ElMessage.error('更新政策失败')
  } finally {
    updating.value = false
  }
}

const handlePublishPolicy = async (policyId) => {
  try {
    await ElMessageBox.confirm('确定要发布这个政策吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await publishPolicy(policyId)
    if (res.code === 200) {
      ElMessage.success('政策发布成功')
      await loadActivePolicies()
      await loadUserAgreements()
      await loadPrivacyPolicies()
    } else {
      ElMessage.error(res.message || '发布失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发布政策失败:', error)
      ElMessage.error('发布政策失败')
    }
  }
}

const handleDeactivatePolicy = async (policyId) => {
  try {
    await ElMessageBox.confirm('确定要停用这个政策吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deactivatePolicy(policyId)
    if (res.code === 200) {
      ElMessage.success('政策停用成功')
      await loadActivePolicies()
      await loadUserAgreements()
      await loadPrivacyPolicies()
    } else {
      ElMessage.error(res.message || '停用失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('停用政策失败:', error)
      ElMessage.error('停用政策失败')
    }
  }
}

const handleDeletePolicy = async (policyId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个政策吗？删除后无法恢复！', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deletePolicy(policyId)
    if (res.code === 200) {
      ElMessage.success('政策删除成功')
      await loadUserAgreements()
      await loadPrivacyPolicies()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除政策失败:', error)
      ElMessage.error('删除政策失败')
    }
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

const refreshPolicies = async () => {
  try {
    ElMessage.info('正在刷新政策内容...')
    await loadActivePolicies()
    await loadUserAgreements()
    await loadPrivacyPolicies()
    ElMessage.success('刷新完成')
  } catch (error) {
    console.error('刷新政策失败:', error)
    ElMessage.error('刷新失败')
  }
}



// 生命周期
onMounted(() => {
  loadActivePolicies()
  loadUserAgreements()
  loadPrivacyPolicies()
})
</script>

<style scoped>
.user-agreement-container {
  padding: 20px;
}

.agreement-card {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.agreement-content {
  margin-top: 20px;
}



.tab-content {
  padding: 20px 0;
  line-height: 1.8;
  color: #606266;
}

.policy-content {
  margin-bottom: 30px;
}

.policy-content h1,
.policy-content h2,
.policy-content h3,
.policy-content h4 {
  color: #303133;
  margin: 20px 0 15px 0;
}

.policy-content p {
  margin: 10px 0;
  text-align: justify;
}

.policy-content ul {
  margin: 10px 0;
  padding-left: 20px;
}

.policy-content li {
  margin: 8px 0;
  text-align: justify;
}

.policy-info {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-top: 20px;
}

.policy-info p {
  margin: 8px 0;
}

.no-content {
  text-align: center;
  padding: 40px 0;
}

.policy-management {
  padding: 20px 0;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

:deep(.el-tabs__content) {
  padding: 20px;
  background-color: #fafafa;
  border: 1px solid #e4e7ed;
  border-top: none;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 